package com.rapida.pet.core;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

public class PetService extends Service implements PetBehavie.IStateChangedSlot {
	private PetBehavieUI mPetBehavieUI;
	private PetBehavie mPetBehavie;
	private PetBinder mPetBinder = new PetBinder();
	private TimerHandler mTimerHandler = new TimerHandler();

	private class TimerHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			mPetBehavie.trigerEvent(PetBehavie.Event.values()[(int) (Math.random() * PetBehavie.Event.values().length)]);
			sendEmptyMessageDelayed(0, 1000);
		}
	}

	@Override
	public void stateChangedSlot(PetBehavie.PetState v) {
		mPetBehavieUI.stateChangedSlot(v);
	}

	public class PetBinder extends Binder {
		public PetService getService(){
			return PetService.this;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return mPetBinder;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		mPetBehavieUI = new PetBehavieUI(this);
		mPetBehavie = new PetBehavie();
		mPetBehavie.registerEvent(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	
	public void start() {
		if (!mPetBehavieUI.isShow()) {
			mPetBehavieUI.start();
		}
	}
	
	public void stop() {
		if (mPetBehavieUI.isShow()) {
			mPetBehavieUI.remove();
		}
	}

	public static class CMD {
		int cmd;
		int value;

		public CMD(int cmd, int value) {
			this.cmd = cmd;
			this.value = value;
		}
	}

	public void commond(CMD cmd) {
		if (cmd.cmd == 0) {
			mTimerHandler.sendEmptyMessageDelayed(0, 1000);
		} else if (cmd.cmd == 1) {
			mPetBehavie.trigerEvent(PetBehavie.Event.values()[cmd.value]);
		} else if (cmd.cmd == 2) {
			mPetBehavie.setCurrentState(PetBehavie.PetState.values()[cmd.value]);
		}

	}
}
